#include<iostream>
#include<unistd.h>
#include<fcntl.h>
#include<errno.h>
using std::cout;
using std::endl;

void SetNonBlock(int fd)
{
    int f1=fcntl(fd,F_GETFL);
    if(f1<0)
    {
        std::cerr<<"获取文件标记位失败..."<<endl;
        return;
    }
    fcntl(fd,F_SETFL,f1|O_NONBLOCK);
}
int main()
{
    char buffer[1024];
    buffer[0];
    SetNonBlock(0);   //设置0文件描述符为非阻塞
    while(true)
    {
        ssize_t s=read(0,buffer,sizeof(buffer));
        if(s>0)
        {
            buffer[s-1]=0;
            cout<<"buffer: "<<buffer<<endl;
        }
        else{
            if(errno==EAGAIN||errno==EWOULDBLOCK)
            {
                sleep(1);
                cout<<"EAGAIN: "<<EAGAIN<<" "<<"EWOULDBLOCK: "<<EWOULDBLOCK<<endl;
                cout<<"当前没有出错，仅仅是底层数据没有就绪罢了。"<<endl;
                continue;
            }
            if(errno==EINTR)
            {
                cout<<"读取信号中断"<<endl;
                continue;
            }
            //走到这一定出错
            std::cerr<<"read error"<<endl;
            break;
        }
    }
    return 0;
}
/* int main()
{
    char buffer[1024];
    buffer[0]=0;
    while(true)
    {
        ssize_t s=read(0,buffer,sizeof(buffer));
        if(s<0)
        {
            std::cerr<<"read error"<<endl;
        }
        else if(s>0)
        {
            buffer[s-1]=0;
            cout<<buffer<<endl;
        }
        else{
            //
        }
    }
    return 0;
} */